package com.hfh.net;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author hfh
 * @Date 2022 09 13 16 44
 **/
public class Text1 {
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9999);

        Socket s =ss.accept();
        InputStream is = s.getInputStream();
        FileOutputStream fos = new FileOutputStream("b.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] arr = new byte[1024];
        int len;
        while ((len= is.read(arr))!=-1){
            bos.write(arr,0,len);
        }

        OutputStream os = s.getOutputStream();
        os.write("发送成功".getBytes());

        os.close();
        bos.close();
        fos.close();
        s.close();
        ss.close();
    }

    @Test
    public void client() throws IOException {
        Socket s = new Socket(InetAddress.getLocalHost(),9999);

        FileInputStream fis = new FileInputStream("a.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = s.getOutputStream();

        byte[] arr = new byte[1024];
        int len;
        while ((len= bis.read(arr))!=-1){
            os.write(arr,0,len);
        }
        s.shutdownOutput();

        InputStream is = s.getInputStream();
        while ((len= is.read(arr))!=-1){
            System.out.println(new String(arr, 0, len));
        }

        is.close();
        os.close();
        bis.close();
        fis.close();
        s.close();
    }
}
